#!/usr/bin/env python3
#-*- coding=utf-8 -*-

import requests
import threading
import os
import hashlib
import time
import signal
import json

POST_URL = "http://%s/minik-rec/file_download.php"
GET_URL = "http://192.168.1.72/test.php"
QUERY_URL = "http://101.37.30.106:8080/query_file.php"
DIR_FILE = "."
QUERY_IP_LOCAL_URL = "http://192.168.1.72:8080/minik_server/query_ip.php" 
QUERY_IP_REMOTE_URL = "http://101.37.30.106/minik_server/query_ip.php" 
global flag 

def getFileMd5(filename):
	if(not os.path.isfile(path)):
		return None
	fp = open(filename, 'rb')
	myhash = hashlib.md5()
	myhash.update(fp.read())
	hash_code = myhash.hexdigest()
	fp.close()
	return hash_code

def postFile(path, result):
	if(type(result) != type(dict()) or result.get('url', None) == None or result.get('key', None) == None):
		print 'empty'
		return
	if(not os.path.isfile(path)):
		print 'os.path.isfile'
		return
	key,extension =  os.path.splitext(os.path.basename(path))
	if extension != ".mp3":
	 	print '!= .mp3'
		return
	files = {'file': open(path, 'rb')}
	header = dict()
	sercret_key = "y4LlG9h7qBil6E*F"
	header['cmd'] = 'upload'

	header['key'] = result['key']
	header['time'] = int(time.time())
	header['file_id'] = "123"
	header['file_type'] = 0
	header['md5'] = 'd79f14a9ae939d9b31725789307ecc76'
	has_str = "%s%s%s%s%d%s" %(header['cmd'], header['key'], header['file_id'], header['md5'], header['time'], sercret_key)
	#print has_str
	header['signature'] = hashlib.sha1(has_str).hexdigest()
#	print header['signature']
	try:
		r = requests.post(result['url'], files=files, headers=header)
#		r = requests.post("http://180.97.83.67/minik-rec/file_download.php", files=files, headers=header)
#		r = requests.post("http://58.240.173.68/minik-rec/file_download.php", files=files, headers=header)
#		r = requests.post("http://180.97.83.70/minik-rec/file_download.php", files=files, headers=header)
		print r.text
	except Exception, e:
		print e
	return
	fp = open("test.log", "a")
	fp.write("\n[%d] " %time.time() + ' ' + r.url + r.text)
	fp.close()
	print(r.url + ' ' + r.text)

def main():
	current_files = os.listdir(DIR_FILE)
	signal.signal(signal.SIGINT, signalHandler)
	global flag
	flag = True
	result = get_upload_url()
	print result, "key"
	postFile("123.mp3", result)
	query_file()
	'''
	while flag:
		for current_file in current_files:
			url_upload = get_upload_url()
			postFile(current_file, url_upload)
	'''

def signalHandler(signum, frame):
	global flag
	flag = False
	print("sigint occur\n")

def get_upload_url():
	sercret_key = "y4LlG9h7qBil6E*F"
	headers = dict() 
	headers['cmd'] = "get_ip";
	headers['time'] = int(time.time());
	has_str = "%s%d%s" %(headers['cmd'], headers['time'], sercret_key);
#	print has_str, "\n"
	headers['signature'] = hashlib.sha1(has_str).hexdigest()
	result = requests.get(QUERY_IP_REMOTE_URL, headers=headers)
	print result.text
	server_reply = result.json()
	if(server_reply.get('status',0) and server_reply.get('info_code', 0) == '10000'):
		result = dict()
		result['url'] = server_reply.get('result', None);
		result['key'] = server_reply.get('key', None);
		return result;
	else:
		return None

def query_file():
	sercret_key = "y4LlG9h7qBil6E*F"
	headers = dict() 
	headers['cmd'] = "query_file";
	headers['time'] = int(time.time());
	headers['file_id'] = '123';
	headers['file_type'] = 0
	has_str = "%s%s%d%s" %(headers['cmd'], headers['file_id'], headers['time'], sercret_key);
#	print has_str, "\n"
	headers['signature'] = hashlib.sha1(has_str).hexdigest()
	result = requests.get(QUERY_URL, headers=headers)
	print result.text

if __name__ == '__main__':
	main()
